Telegram Group & Telegram Channel
🖥 Задача «Перехват исключений и потеря контекста» (C# 12)

Дан код:


using System;
using System.Runtime.ExceptionServices;

class Program
{
static void Main()
{
try
{
Console.WriteLine(Foo());
}
catch (Exception ex)
{
Console.WriteLine($"Catch: {ex.Message}");
}
}

static int Foo()
{
try
{
return Bar();
}
finally
{
throw new Exception("finally in Foo");
}
}

static int Bar()
{
try
{
throw new Exception("error in Bar");
}
finally
{
Console.WriteLine("Bar finally executed");
}
}
}


Вопросы:
• Что напечатает программа и почему?
• В каком порядке выполняются блоки try / finally?
• Какая из двух ошибок дойдёт до catch, а какая потеряется?
• Как изменить код, чтобы не терять информацию о первой ошибке?

Разбор:
• Bar бросает Exception("error in Bar"). Прежде чем исключение покинет метод, выполняется его finally, выводя Bar finally executed.
• Управление переходит в Foo. Там срабатывает finally, который бросает новое исключение ("finally in Foo").
• По правилам CLR новое исключение из finally заменяет текущее. Первая ошибка пропадает.
• В Main перехватывается только «finally in Foo».

Консольный вывод:

Bar finally executed
Catch: finally in Foo

Как сохранить обе ошибки

Обернуть второе исключение так, чтобы первая причина не потерялась, например:


finally
{
var pending = new Exception("finally in Foo");
throw new AggregateException("Foo failed", pending);
}


или переслать исходное исключение через ExceptionDispatchInfo:

Exception pending = null;

static int Foo()
{
try
{
return Bar();
}
catch (Exception ex)
{
pending = ex; // сохраняем первую причину
throw;
}
finally
{
if (pending != null)
ExceptionDispatchInfo.Capture(pending).Throw();
}
}```

Так ни одна ошибка не будет потеряна, а отладка станет нагляднее.
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/csharp_1001_notes/710
Create:
Last Update:

🖥 Задача «Перехват исключений и потеря контекста» (C# 12)

Дан код:


using System;
using System.Runtime.ExceptionServices;

class Program
{
static void Main()
{
try
{
Console.WriteLine(Foo());
}
catch (Exception ex)
{
Console.WriteLine($"Catch: {ex.Message}");
}
}

static int Foo()
{
try
{
return Bar();
}
finally
{
throw new Exception("finally in Foo");
}
}

static int Bar()
{
try
{
throw new Exception("error in Bar");
}
finally
{
Console.WriteLine("Bar finally executed");
}
}
}


Вопросы:
• Что напечатает программа и почему?
• В каком порядке выполняются блоки try / finally?
• Какая из двух ошибок дойдёт до catch, а какая потеряется?
• Как изменить код, чтобы не терять информацию о первой ошибке?

Разбор:
• Bar бросает Exception("error in Bar"). Прежде чем исключение покинет метод, выполняется его finally, выводя Bar finally executed.
• Управление переходит в Foo. Там срабатывает finally, который бросает новое исключение ("finally in Foo").
• По правилам CLR новое исключение из finally заменяет текущее. Первая ошибка пропадает.
• В Main перехватывается только «finally in Foo».

Консольный вывод:

Bar finally executed
Catch: finally in Foo

Как сохранить обе ошибки

Обернуть второе исключение так, чтобы первая причина не потерялась, например:


finally
{
var pending = new Exception("finally in Foo");
throw new AggregateException("Foo failed", pending);
}


или переслать исходное исключение через ExceptionDispatchInfo:

Exception pending = null;

static int Foo()
{
try
{
return Bar();
}
catch (Exception ex)
{
pending = ex; // сохраняем первую причину
throw;
}
finally
{
if (pending != null)
ExceptionDispatchInfo.Capture(pending).Throw();
}
}```

Так ни одна ошибка не будет потеряна, а отладка станет нагляднее.

BY C# 1001 notes


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/csharp_1001_notes/710

View MORE
Open in Telegram


C 1001 notes Telegram | DID YOU KNOW?

Date: |

How To Find Channels On Telegram?

There are multiple ways you can search for Telegram channels. One of the methods is really logical and you should all know it by now. We’re talking about using Telegram’s native search option. Make sure to download Telegram from the official website or update it to the latest version, using this link. Once you’ve installed Telegram, you can simply open the app and use the search bar. Tap on the magnifier icon and search for a channel that might interest you (e.g. Marvel comics). Even though this is the easiest method for searching Telegram channels, it isn’t the best one. This method is limited because it shows you only a couple of results per search.

Telegram Gives Up On Crypto Blockchain Project

Durov said on his Telegram channel today that the two and a half year blockchain and crypto project has been put to sleep. Ironically, after leaving Russia because the government wanted his encryption keys to his social media firm, Durov’s cryptocurrency idea lost steam because of a U.S. court. “The technology we created allowed for an open, free, decentralized exchange of value and ideas. TON had the potential to revolutionize how people store and transfer funds and information,” he wrote on his channel. “Unfortunately, a U.S. court stopped TON from happening.”

C 1001 notes from tw


Telegram C# 1001 notes
FROM USA